package com.user.service.impl;

import com.common.entity.sys.Dict;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.user.mapper.DictMapper;
import com.user.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 温洁宇
 * @date: 2021/08/11/19:02
 * Other:
 */
@Service
public class IDictServiceImpl implements IDictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    public PageInfo<Dict> findAll(Dict dict, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Dict> root = dictMapper.findAll(dict);
        List<Dict> list = root.stream().filter(e -> {
            return e.getParentId() == 0;
        }).map(menu -> {
            menu.setChildren(addChildren(menu,root));
            return menu;
        }).collect(Collectors.toList());
        return new PageInfo<>(list);
    }

    @Override
    public boolean addChildren(Dict dict) {
        if (dict.getParentId() == null) {
            List<Dict> list = dictMapper.findOne(0);
            Dict last = list.get(list.size() - 1);
            dict.setId(last.getId() + 1000);
            dict.setParentId(0);
        } else {
            List<Dict> one = dictMapper.findOne(dict.getParentId());
            dict.setId(dict.getParentId() + one.size() +1);
        }
        dict.setCreateTime(new Date());
        dict.setUpdateTime(new Date());
        dictMapper.addChildren(dict);
        return true;
    }

    @Override
    public List<Dict> findOne(int parentId) {
        return dictMapper.findOne(parentId);
    }

    @Override
    public Dict findOneById(int id) {
        return dictMapper.findOneById(id);
    }

    @Override
    public boolean delOne(int id) {
        return dictMapper.delOne(id);
    }

    private List<Dict> addChildren(Dict curr,List<Dict> root) {
        List<Dict> childrenList = root.stream().filter(e -> {
            return e.getParentId().equals(curr.getId());
        }).map(child -> {
            child.setChildren(addChildren(child, root));
            return child;
        }).collect(Collectors.toList());
        return childrenList;
    }
}
